package com.atguigu.gulimall.gateway.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

/**
 * User: haitao
 * Date: 2020/6/15
 */
@Configuration
public class GuliMallCorsConfiguration {
    @Bean
    public CorsWebFilter corsWebFilter() {
        UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        /**
         * 效果是 预检请求（OPTIONS）
         * Access-Control-Allow-Credentials: true
         * Access-Control-Allow-Headers: content-type, token
         * Access-Control-Allow-Methods: POST
         * Access-Control-Allow-Origin: http://localhost:8001
         * 就会带上这些东西，然后符合了js的同源策略 所以就会发送真实的请求。
         */
        corsConfiguration.addAllowedOrigin("*"); // 给所有源都添加
        corsConfiguration.addAllowedHeader("*"); // 允许所有的请求头
        corsConfiguration.addAllowedMethod("*"); // 允许所有的方法
        corsConfiguration.setAllowCredentials(true);// cookie
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**",corsConfiguration); // 为所有请求添加跨域配置
        CorsWebFilter corsWebFilter = new CorsWebFilter(urlBasedCorsConfigurationSource);
        return corsWebFilter;
    }
}
